package com.sunop.panticlass.properties;

import cn.dev33.satoken.stp.StpUtil;
import com.sunop.panticlass.mapper.UserMapper;
import org.springframework.stereotype.Component;
import java.util.Arrays;

@Component
public class DynamicQueueResolver {
    private final UserMapper userMapper;

    public DynamicQueueResolver(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public String[] resolveQueues() {
        // 1. 安全检查：如果Sa-Token未初始化，直接返回空队列
        try {
            if (!isSaTokenReady() || !StpUtil.isLogin()) {
                return new String[0];
            }

            // 2. 获取当前用户关联的班级ID
            int userId = StpUtil.getLoginIdAsInt();
            String classIds = String.valueOf(userMapper.getclassId(userId)); // 格式如 "1,2,3"

            // 3. 生成队列名称
            return Arrays.stream(classIds.split(","))
                    .map(id -> "class.queue." + id.trim())
                    .toArray(String[]::new);

        } catch (Exception e) {
            return new String[0]; // 任何异常都降级处理
        }
    }

    // 检查Sa-Token上下文是否就绪
    private boolean isSaTokenReady() {
        try {
            return StpUtil.getTokenName() != null; // 简单有效的检查方式
        } catch (Exception e) {
            return false;
        }
    }
}